package org.hhq.demo.config.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Configuration
public class GlobalFilterConfig{

    /**
     * 前置过滤
     */
    @Order(0)
    @Bean
    public GlobalFilter tokenFilter(){
        return (exchange,chain)->{
            //pre
            List<String> tokens = exchange.getRequest().getHeaders().get("token");
            if (!CollectionUtils.isEmpty(tokens)){
                return Mono.error(new Throwable("token无效"));
            }
            return chain.filter(exchange);
        };
    }

    /**
     * 后置过滤
     */
    @Bean
    @Order(1)
    public GlobalFilter logPrintFilter(){
        return ((exchange, chain) -> {
            return chain.filter(exchange).then(Mono.fromRunnable(()->{
                //post
                log.info("logPrintFilter");
            }));
        });
    }
}
